'''
 视频提取图片
'''
import os

import cv2


def videotoimg(path, newPath, jump_count_start, jump_count_end, step):
    if not os.path.exists(newPath):
        os.makedirs(newPath)
    for dirpath, dirnames, filenames in os.walk(path):
        for filename in filenames:
            if not str(filename).lower().endswith(".mp4") and not str(filename).lower().endswith(".avi"):
                continue
            print("处理视频：" + os.path.join(path, filename))
            cam1 = cv2.VideoCapture(os.path.join(path, filename))
            # 获取视频1的宽度
            ww = int(cam1.get(3))
            # 获取视频1的高度
            hh = int(cam1.get(4))
            print(ww, hh)
            # if ww < 1920:
            #     print('跳过！' )
            #     continue
            # 获取视频的帧频
            CAMERA_FPS = cam1.get(cv2.CAP_PROP_FPS)  # 25帧/秒
            print('帧频:' + str(CAMERA_FPS))
            # 获取视频的帧数
            CAP_PROP_FRAME_COUNT = cam1.get(cv2.CAP_PROP_FRAME_COUNT)  # 25帧/秒
            print("帧数：" + str(CAP_PROP_FRAME_COUNT))
            # 定义视频编码格式
            fourcc = cv2.VideoWriter_fourcc(*'mp4v')
            num = 0
            while True:
                if num >= CAP_PROP_FRAME_COUNT - jump_count_end * CAMERA_FPS:
                    break
                # 读取视频
                (ok1, frame1) = cam1.read()
                if num < jump_count_start * CAMERA_FPS or (num - jump_count_start * CAMERA_FPS) % step != 0:
                    num += 1
                    continue
                # 视频最后一秒不参与合并到新视频
                # frame1=frame1 * 0.4
                # if ww<hh:
                #     frame1=np.concatenate([frame1, frame1, frame1], axis=1)
                if ok1:
                    cv2.imwrite(os.path.join(newPath, filename + str(num) + '.jpg'), frame1)
                    num += 1
                else:
                    print(num)
                    break
            cam1.release()
            cv2.destroyAllWindows()


if __name__ == '__main__':
    # 视频所在文件夹路径
    path = r'D:\11'
    # 提取为图片后保存文件夹路径
    newPath = r'D:\yangxiaolong'
    videotoimg(path, newPath, 0, 0, 1)
